// server/app/model/supplier_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT, DECIMAL } = app.Sequelize;

  const Supplier = app.model.define('supplier', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,  // 不再允许为空，确保多租户数据隔离
      field: 'organization_id',
      comment: '组织ID'
    },
    name: {
      type: STRING(100),
      allowNull: false,
      unique: true,
      comment: '供应商名称'
    },
    contactPerson: {
      type: STRING(50),
      allowNull: true,
      field: 'contact_person',  // 改为下划线命名
      comment: '联系人'
    },
    phone: {
      type: STRING(50),
      allowNull: true,
      field: 'phone',
      comment: '联系电话'
    },
    email: {
      type: STRING(100),
      allowNull: true,
      field: 'email',
      comment: '邮箱'
    },
    address: {
      type: STRING(200),
      allowNull: true,
      field: 'address',
      comment: '地址'
    },
    remark: {
      type: TEXT,
      allowNull: true,
      field: 'remark',
      comment: '备注'
    },
    status: {
      type: STRING(20),
      defaultValue: 'pending',
      field: 'status',
      comment: '状态: pending-待审核, active-合作中, suspended-已暂停, terminated-已终止'
    },
    rating: {
      type: DECIMAL(3, 2),
      allowNull: true,
      defaultValue: 0.00,
      field: 'rating',
      comment: '供应商评分'
    },
    cooperationDate: {
      type: DATE,
      allowNull: true,
      field: 'cooperation_date',  // 改为下划线命名
      comment: '合作开始时间'
    },
    createdAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'created_at',  // 改为下划线命名
      comment: '创建时间'
    },
    updatedAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'updated_at',  // 改为下划线命名
      comment: '更新时间'
    }
  }, {
    tableName: 'suppliers',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  });

  // 添加关联关系
  Supplier.associate = function() {
    // 供应商与组织的关联
    if (app.model.OrganizationModel) {
      Supplier.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }
  };

  return Supplier;
};